package com.tkwayne.ftpclient.core;
 
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;

/**
 * FTPClientPool
 * get FTPClient from FTPClientPool
 * eg.
 * Object obj = null;
 * try{
 *   obj = pool.borrowObject();
 *   obj.methodA();
 * }catch(Exception e){
 *
 * }finally{
 *    pool.returnObject(obj);
 * }
 * @author wayne
 * @description 
 * @date 2019/7/20 16:43
 */
public class FTPClientPool {
	
	/**
	 * Ftp客户端连接池
	 */
    private GenericObjectPool<FTPClient> pool;

    /**
     * Ftp客户端工厂
     */
    private FTPClientFactory clientFactory;

    public FTPClientPool(FTPClientFactory clientFactory){
	    this.clientFactory=clientFactory;
 	    pool = new GenericObjectPool<FTPClient>(clientFactory, clientFactory.getFtpPoolConfig()
				,clientFactory.getFtpAbandonedConfig());
    }

	public FTPClientFactory getClientFactory() {
		return clientFactory;
	}

	public GenericObjectPool<FTPClient> getPool() {
		return pool;
	}


	/**
	 * 初始化MaxIdle个链接
	 * @return
	 * @throws Exception
	 */
	public void initPool() throws Exception {
		for(int i = 0; i < clientFactory.getFtpPoolConfig().getMaxIdle(); i++){
			pool.addObject();
		}
	}

	/**
	 * 获取一个连接对象
	 * @return
	 * @throws Exception
	 */
    public FTPClient borrowObject() throws Exception {
    	return pool.borrowObject();
    }

    /**
     * 归还一个连接对象
     * @param ftpClient
     */
    public void returnObject(FTPClient ftpClient) {
    	if(ftpClient != null){
    		pool.returnObject(ftpClient); 
    	}
    }
}